package com.heimao;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
public class HelloController {

    /***************该部分可以把spring-servlet.xml的试图解析器删除掉，交给requst和respone进行原生转发重定向页面*************************/
    // 访问示例: http://localhost:8080/m/v1
    @RequestMapping("/m/v1")
    public void test1(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session=request.getSession();
        System.out.println(session.getId());
        response.getWriter().println("页面输出内容");
    }
    // 访问示例: http://localhost:8080/m/v2
    @RequestMapping("/m/v2")
    public void test2(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //重定向
        response.sendRedirect("index.jsp");

    }
    // 访问示例: http://localhost:8080/m/v3
    @RequestMapping("/m/v3")
    public void test3(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        //转发
        request.setAttribute("msg","通过原生转发方式到的该页面");
        request.getRequestDispatcher("/index.jsp").forward(request,response);
    }

/******springMVC重定向和转发示例：该部分可以把spring-servlet.xml的试图解析器删除掉，交给requst和respone进行原生转发重定向页面***********/
// 访问示例: http://localhost:8080/m/v4?userName=黑猫
    @RequestMapping("/m/v4")
    public String test4(@RequestParam("userName") String name, Model model) throws IOException {
        model.addAttribute("msg","通过springmvc的默认转发,参数为"+name);

        return "/index.jsp";
    }
    // 访问示例: http://localhost:8080/m/v5
    @RequestMapping("/m/v5")
    public String test5(Model model) throws IOException {
            //重定向
        return "redirect:/index.jsp";
    }
    // 访问示例: http://localhost:8080/m/v6
    @RequestMapping("/m/v6")
    public String test6(Model model) throws IOException {
        model.addAttribute("msg","通过springmvc 声明式的转发");
        return "forward:/index.jsp";
    }

}
